package com.mission.game.playgame;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;

import com.mission.game.R;
import com.mission.game.utils.PictureTask;
import com.mission.game.utils.Task;

public class PlayPictureTask extends PlayAbstractTask {

	private static int TAKE_PICTURE = 0;
	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	ImageView _mImageView;

	@Override
	protected int getContentView() {
		return R.layout.play_picture_task;
	}


	@Override
	protected int getNameInput() {
		return R.id.play_picture_name;
	}


	@Override
	protected int getDescriptionInput() {
		return R.id.play_picture_description;
	}


	@Override
	protected void setSpecificFields() {
		_mImageView = (ImageView) findViewById(R.id.play_picture_input);
		if(!((PictureTask)_task).getPictureFile().isEmpty())
		{
			Bitmap bitmap = BitmapFactory.decodeFile(((PictureTask)_task).getPictureFile());
			_mImageView.setImageBitmap(bitmap);
		}
	}

	public void onTakePictureClicked(View v) {
		dispatchTakePictureIntent(TAKE_PICTURE);
	}
	
	@Override
	public void onBackToMissionClicked(View v) {
		_task.setStatus(Task.Status.COMPLETED); // DEMO MODE! TODO: remove for production 
		getIntent().putExtra("task", _task);
		setResult(RESULT_OK, getIntent());
		finish();
	}

	private void dispatchTakePictureIntent(int actionCode) {
		Intent takePictureIntent = new Intent(
				MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(takePictureIntent, actionCode);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent takePictureIntent) {
		super.onActivityResult(requestCode, resultCode, takePictureIntent);

		File f;
		try {
			f = createImageFile();
			takePictureIntent
					.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

			Bundle extras = takePictureIntent.getExtras();
			Bitmap mImageBitmap = (Bitmap) extras.get("data");
			if (mImageBitmap != null && mImageBitmap.getHeight() > 0) {
				((PictureTask)_task).setPictureFile(f.getAbsolutePath());
				_mImageView.setImageBitmap(mImageBitmap);
				_task.setStatus(Task.Status.COMPLETED);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private File createImageFile() throws IOException {
		// timeStamp is for collision-resistant files, do we need it?
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + "MISSIONGAME_" + timeStamp;
		File image = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX);
		return image;
	}
}
